<?php
declare(strict_types=1);

namespace App\Common\Extend\Guard\Drives;

use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\Redis;
use RedisException;
use Zms\Unit\Json;
use function Hyperf\Support\env;

class RedisDrives implements DrivesInterface
{
    protected string $key;

    #[Inject]
    protected Redis $redis;

    public function __construct()
    {
        $this->key = env('APP_NAME') . ':guard:';
    }

    /**
     * 设置缓存key
     * @param string $key
     * @return string
     */
    protected function setKey(string $key): string
    {
        if (str_starts_with($key, $this->key)) {
            return $key;
        }
        return $this->key . $key;
    }


    public function get(string $key): mixed
    {
        $data = $this->redis->get($this->setKey($key));
        if ($data) {
            $data = Json::decode($data);
            return $data['value'] ?? null;
        }
        return null;
    }


    /**
     * 储存数据
     * @param string $key
     * @param mixed $data
     * @param int $ttl
     * @return void
     * @throws RedisException
     */
    public function set(string $key, mixed $data, int $ttl = 0)
    {
        $value = Json::encode(['value' => $data]);
        $this->redis->set($this->setKey($key), $value, $ttl ? $ttl : null);
    }


    /**
     * 删除数据
     * @param array|string $keys
     * @return void
     * @throws RedisException
     */
    public function delete(array|string $keys)
    {
        if (is_string($keys)) {
            $keys = [$keys];
        }
        $keyAll = [];
        foreach ($keys as $key) {
            $keyAll[] = $this->setKey($key);
        }
        $this->redis->del($keyAll);
    }
}